package com.power.using.myapplication.base;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jaeger.library.StatusBarUtil;
import com.power.using.myapplication.R;
import com.power.using.myapplication.interfaces.DialogClick;
import com.power.using.myapplication.swipeview.SwipeBackActivityBase;
import com.power.using.myapplication.swipeview.SwipeBackActivityHelper;
import com.power.using.myapplication.swipeview.SwipeBackLayout;
import com.power.using.myapplication.swipeview.Utils;
import com.power.using.myapplication.utils.ToastUtils;
import com.power.using.myapplication.utils.loading.IosAlertDialog;
import com.power.using.myapplication.utils.loading.LoadingDialog;
import com.power.using.myapplication.view.SelectDialogView;
import com.zhy.autolayout.AutoLayoutActivity;

import butterknife.ButterKnife;
import butterknife.Unbinder;

//import com.jaeger.library.StatusBarUtil;

/**
 * sometimes I believe compiler ignores all my comments
 * Created by gyyak46 on 2017/3/4.
 * <p>
 * 添加 loading toast settitle eventbus 加载动画 取消加载动画
 */

public abstract class BaseScanActivity extends AutoLayoutActivity implements SwipeBackActivityBase {

    private static final String TAG = "BaseActivity";

    private Handler mHandler = new Handler();
    ImageView mBack;
    TextView mTitle;
    ImageView mIv_menu;
    TextView mTv_menu;
    Toolbar mToolbar;

    protected Activity mActivity;
    private Unbinder bind;
    private GestureDetector mGestureDetector;
    private SwipeBackActivityHelper mHelper;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mActivity = this;
        requestWindowFeature(Window.FEATURE_NO_TITLE);

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//
//            //透明状态栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            //透明导航栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//
//            // 创建状态栏的管理实例
//            SystemBarTintManager tintManager = new SystemBarTintManager(this);
//            // 激活状态栏设置
//            tintManager.setStatusBarTintEnabled(true);
//            tintManager.setStatusBarTintColor(getResources().getColor(R.color.blue_300));
//
//        }
//        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            Window window = getWindow();
//            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
//                                 | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                                               | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            window.setStatusBarColor(Color.TRANSPARENT);
////            window.setNavigationBarColor(Color.TRANSPARENT);
//        }

        //
        setStatusBar();

        Log.e("this", mActivity.getLocalClassName());

//        ActivityManager.getInstance().addActivity(this);

//        EventBus.getDefault().register(this);
        //初始布局
        initContentView(savedInstanceState);

        bind = ButterKnife.bind(this);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        if (null != mToolbar) {
            setSupportActionBar(mToolbar);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            initTitle();
        }
        //swipeBackActivityHelepr
        mHelper = new SwipeBackActivityHelper(this);
        mHelper.onActivityCreate();

//        initGestureDetector();
        initView();

        initLogic();
    }



    protected void setStatusBar() {
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_300));
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mHelper.onPostCreate();
    }

    @Override
    public SwipeBackLayout getSwipeBackLayout() {
        return mHelper.getSwipeBackLayout();
    }

    @Override
    public void setSwipeBackEnable(boolean enable) {
        getSwipeBackLayout().setEnableGesture(enable);
    }

    @Override
    public void scrollToFinishActivity() {
        Utils.convertActivityToTranslucent(this);
        getSwipeBackLayout().scrollToFinishActivity();
    }

    @Override
    public View findViewById(int id) {
        View v = super.findViewById(id);
        if (v == null && mHelper != null) {
            return mHelper.findViewById(id);
        }
        return v;
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
//        mGestureDetector.onTouchEvent(event);
        return super.onTouchEvent(event);
    }


    protected void startActivity(Class activity) {
        Intent intent = new Intent(this, activity);
        startActivity(intent);

    }


    /**
     * 用来添加布局文件
     *
     * @param savedInstanceState
     */
    protected abstract void initContentView(Bundle savedInstanceState);

    /**
     * 初始化控件
     */
    protected abstract void initView();

    /**
     * 处理逻辑
     */
    protected abstract void initLogic();

    /**
     * Bundle  传递数据
     *
     * @param extras
     */
    protected abstract void getBundleExtras(Bundle extras);


    protected void initTitle() {
        mTitle = (TextView) findViewById(R.id.toolbar_title);
        mBack = (ImageView) findViewById(R.id.toolbar_back);
        mBack.setVisibility(View.GONE);
        mIv_menu = (ImageView) findViewById(R.id.toolbar_iv_menu);
        mTv_menu = (TextView) findViewById(R.id.toolbar_tv_menu);
//        if (null != mBack) {
//            mBack.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    finish();
//                }
//            });
//        }
    }

    /**
     * 添加菜单按钮
     *
     * @param resource
     */
    public void setTitleMenu(int resource) {
        if (mIv_menu != null) {
            mIv_menu.setImageResource(resource);
        }
    }

    /**
     * 设置title标题
     *
     * @param string
     */
    public void setTitle(String string) {
        if (null != mTitle) {
            mTitle.setText(string);
        }
    }

    /**
     * 设置title标题
     *
     * @param id
     */
    @Override
    public void setTitle(int id) {
        if (null != mTitle) {
            mTitle.setText(id);
        }
    }

    /**
     * EventBus接收消息
     *
     * @param center 消息接收
     */
//    @Subscribe
//    public void onEventMainThread(EventCenter center) {
//
//        if (null != center) {
//            onEventComing(center);
//        }
//    }

    /**
     * EventBus接收消息
     *

     * 获取事件总线信息
     */
//    protected abstract void onEventComing(EventCenter center);



    /*
    * 显示旋转加载动画*/
    protected void showProgressloading() {
        SelectDialogView view = new SelectDialogView(this);
        view.createLoadingDialog(this, "正在加载···");
    }

    protected void cancelProgressLoading() {
        SelectDialogView.cancle();
    }

    /**
     * 显示加载动画 默认加载文字
     *
     * @param type
     */
    protected void showLoadingDialog(int type) {
        LoadingDialog.showLoadingDialog(this, type);
    }

    /**
     * 显示加载动画 默认加载文字，自定义图片
     *
     * @param type
     */
    protected void showLoadingDialog(int type, int drawableId) {
        LoadingDialog.showLoadingDialog(this, type, drawableId);
    }

    /**
     * 显示默认加载动画 自定义加载文字
     *
     * @param str
     */
    protected void showLoadingDialog(String str) {
        LoadingDialog.showLoadingDialog(this, str);
    }

    /**
     * 显示加载动画 自定义加载文字
     *
     * @param type
     * @param str
     */
    protected void showLoadingDialog(int type, String str) {
        LoadingDialog.showLoadingDialog(this, type, str);
    }

    /**
     * 显示加载动画 自定义加载文字 自定义图片(只对YzsDialog有效果)
     *
     * @param type
     * @param str
     */
    protected void showLoadingDialog(int type, String str, int drawable) {
        LoadingDialog.showLoadingDialog(this, type, str, drawable);
    }

    /**
     * 取消加载动画
     */
    protected void cancelLoadingDialog() {
        LoadingDialog.cancelLoadingDialog();
    }

    protected void showAlertDialog(Context context, String titleContent, String message, final DialogClick dialogClick) {

        new IosAlertDialog(context).builder().setTitle(titleContent)
                .setMsg(message)
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogClick.PositiveMessage();
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogClick.NegativeMessage();
            }
        }).show();
    }

    // 这
    protected void showAlertDialog2(Context context, String titleContent, String message, final DialogClick dialogClick) {

        new IosAlertDialog(context).builder().setTitle(titleContent)
                .setMsg(message)
                .setCancelable(false)
                .setPositiveButton("立即更新", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogClick.PositiveMessage();
                    }
                }).setNegativeButton("暂不更新", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogClick.NegativeMessage();
            }
        }).show();
    }

    protected void showAlertOnlyPos(Context context, String title, String msg) {
        new IosAlertDialog(context).builder()
                .setMsg(msg)
                .setOnlyPostivite("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).show();
    }

    protected void showAlertOnlyPos2(Context context, String title, String msg, final DialogClick dialogClick) {
        new IosAlertDialog(context).builder()
                .setMsg(msg)
                .setOnlyPostivite("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogClick.PositiveMessage();
                    }
                }).show();
    }


    protected void showAlertPos(Context context, String title, String msg, final DialogClick dialogClick) {
        new IosAlertDialog(context).builder()
                .setMsg(msg)
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogClick.PositiveMessage();
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogClick.NegativeMessage();
            }
        }).show();
    }

    protected void showAlertDialogNoMsg(Context context, String titleContent, String message, final DialogClick dialogClick) {

        new IosAlertDialog(context).builder().setTitle(titleContent)
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogClick.PositiveMessage();
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogClick.NegativeMessage();
            }
        }).show();
    }


    //Toast显示
    protected void showShortToast(String string) {
        ToastUtils.showShortToast(this, string);
    }

    protected void showShortToast(int stringId) {
        ToastUtils.showShortToast(this, stringId);
    }


    //软键盘监听
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v.getWindowToken());
            }
        }
//        mGestureDetector.onTouchEvent(ev);
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 隐藏软件盘方法
     *
     * @param token
     */
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    // 返回
/*
*
    private long lastBackTime = 0;

    private static final long TIME_INTERVAL = 2 * 1000;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (this instanceof MainActivity || this instanceof LoginActivity) {
            cancelLoadingDialog();
            if (keyCode == KeyEvent.KEYCODE_BACK) {

                long currentBackTime = System.currentTimeMillis();
                if (currentBackTime - lastBackTime > TIME_INTERVAL) {
                    lastBackTime = currentBackTime;
                } else {
                    ActivityManager.getInstance().finishAllActivity();
                    finish();
                }
                return true;
            }

//        } else {
//            if (keyCode == KeyEvent.KEYCODE_DEL) {
//            finish();
//            overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
//            }
//        }
        return super.onKeyDown(keyCode, event);
    }

* */

    @Override
    protected void onResume() {
        super.onResume();

    }


    @Override
    protected void onStart() {
        super.onStart();
        Log.e("onResume", "onStart+againRequestdate");
//        if (!(this instanceof LoginActivity)) {
//            Log.e("显示", "LoginActivity+againRequestdate");
//            if (!(this instanceof SettingActivity)) {
//                Log.e("显示", "SettingActivity+againRequestdate");
//                aginRequestDate();
//            }
//        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        bind.unbind();
//        EventBus.getDefault().unregister(this);
//        ActivityManager.getInstance().finishActivity(this);

    }


}
